#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author : sixther.me
#date : 2014-10-03
import os
import sys
import MySQLdb
import threading

#os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'

DBHost='172.16.1.196'
DBName='zabbix'
DBUser='zabbix'
DBPassword='xxxxxxxxxxxxxxxx'

history_tables=['history','history_str','history_text','history_uint']
zabbix_conn=MySQLdb.connect(host='172.16.1.196',user='zabbix',passwd='xxxxxxxxxxxxxx',db='zabbix',charset='utf8')
time_stamp=3600

def execute_sql(sql):
        zabbix_cursor=zabbix_conn.cursor()
        zabbix_cursor.execute(sql)
        result='%s' % zabbix_cursor.fetchone()
        zabbix_cursor.close()
        return result

def get_item_update_percent():
	total_update_item_num=0
	for i in history_tables:
		query_update_item_sql='select count(distinct itemid) from ' +  i + ' where clock > UNIX_TIMESTAMP() - ' + str(time_stamp)
		total_update_item_num += int(execute_sql(query_update_item_sql))
	query_total_item_num="select count(*) from items,hosts where items.hostid=hosts.hostid and hosts.available=1 and hosts.status=0 and items.state=0 and items.status=0"
	total_item_num=execute_sql(query_total_item_num)
	print "%.2f" % (float(total_update_item_num) / float(total_item_num) * float(100))
def get_nvps():
	all_update_item_num=0
	for i in history_tables:
                query_update_item_sql='select count(*) from ' +  i + ' where clock > UNIX_TIMESTAMP() - ' + str(time_stamp)
                all_update_item_num += int(execute_sql(query_update_item_sql))
	print "%.2f" % (float(all_update_item_num) / time_stamp)
def get_error_item_num():
	query_error_item_sql="select count(*) from items where items.error <> '' and items.status<>1;"
	print int(execute_sql(query_error_item_sql))
def get_error_host_num():
	query_error_host_sql="select count(*) from hosts where hosts.error <> '' and hosts.status<>1;"
	print int(execute_sql(query_error_host_sql))
if __name__ ==  '__main__':
	status_data_array={
                'item_update_percent' : 'get_item_update_percent()',
                'nvps' : 'get_nvps()',
		'error_item_num' : 'get_error_item_num()',
		'error_host_num' : 'get_error_host_num()'
	}
	eval(status_data_array[sys.argv[1]])	
	



